﻿using CustomItem;
using Exiled.API.Features.Pickups.Projectiles;
using Exiled.Events.EventArgs.Item;
using Exiled.Events.EventArgs.Player;
using InventorySystem.Items;
using InventorySystem.Items.Firearms;
using InventorySystem.Items.Pickups;
using InventorySystem.Items.ThrowableProjectiles;
using MapGeneration;
using RgCore.PlayerHud;
using System;
using System.Collections.Generic;
using CustomItem.Interfaces;
using UnityEngine;

namespace GrenadeLauncher
{
    [ItemInfo("榴弹发射器", ItemType.GunRevolver)]
    public class GrenadeLauncher : CustomItem.CustomItem, IRoundStartSpawn
    {
        public GrenadeLauncher(ushort serial, bool active = true, ItemBase ib = null, ItemPickupBase ipb = null) : base(
            serial, active, ib, ipb)
        {
        }

        public float Damage { get; set; } = 0.0001f;

        public SpawnRule Rule => new SpawnRule
        {
            StackSpawn = false,
            SpawnableRooms = Array.Empty<RoomName>(),
            MaxStacks = 0,
            Offset = 0,
            SpawnCount = 1,
            SpawnChance = 1,
            SpawnableStructures = new Structure[] { Structure.LargeGun }
        };

        public override void Item_Onactive()
        {
            base.Item_Onactive();
            Exiled.Events.Handlers.Player.UnloadingWeapon += Player_UnloadingWeapon;
            Exiled.Events.Handlers.Player.Shooting += Player_Shooting;
            Exiled.Events.Handlers.Item.ChangingAttachments += Item_ChangingAttachments;
            FirearmStatus status =
                new FirearmStatus(4, FirearmStatusFlags.MagazineInserted | FirearmStatusFlags.Chambered, 594);

            if (PickupBase is FirearmPickup pickup)
            {
                pickup.Distributed = true;
                pickup.NetworkStatus = status;
            }
            else if (Base is Firearm firearm)
            {
                firearm.Status = status;
            }
        }

        public override void Item_Ondeactive()
        {
            base.Item_Ondeactive();
            Exiled.Events.Handlers.Player.UnloadingWeapon -= Player_UnloadingWeapon;
            Exiled.Events.Handlers.Player.Shooting -= Player_Shooting;
            Exiled.Events.Handlers.Item.ChangingAttachments -= Item_ChangingAttachments;
        }

        private void Item_ChangingAttachments(ChangingAttachmentsEventArgs ev)
        {
            if (ev.Item.Serial == Serial)
            {
                ev.IsAllowed = false;
                ev.Player.SendFormattedMsg("item", "<color=#01F1F1>自定义物品</color>", "此武器配件已锁定", 2,
                    MsgType.Failed_Response, ScreenLocation.CenterTop, true);
            }
        }

        private void Player_Shooting(ShootingEventArgs ev)
        {
            if (ev.Item.Serial == Serial)
            {
                bool explode = UnityEngine.Random.Range(0f, 1f) <= Damage;
                ExplosionGrenade grenade;
                if (explode)
                {
                    Damage += 0.05f;
                    grenade = Projectile.CreateAndSpawn(Exiled.API.Enums.ProjectileType.FragGrenade,
                            ev.Player.CameraTransform.position, ev.Player.CameraTransform.rotation, true, ev.Player)
                        .Base as ExplosionGrenade;
                }
                else
                {
                    Damage += 0.02f;
                    grenade = Projectile.CreateAndSpawn(Exiled.API.Enums.ProjectileType.FragGrenade,
                        ev.Player.CameraTransform.position + ev.Player.CameraTransform.forward * 2f,
                        ev.Player.CameraTransform.rotation, true, ev.Player).Base as ExplosionGrenade;
                    Rigidbody rb = (grenade.PhysicsModule as PickupStandardPhysics).Rb;
                    rb.centerOfMass = Vector3.zero;
                    rb.velocity = ev.Player.CameraTransform.forward * 20f;
                }

                List<Keyframe> keyframes = new List<Keyframe>();
                foreach (var a in grenade._playerDamageOverDistance.keys)
                {
                    var key = a;
                    key.value *= 0.3f;
                    keyframes.Add(key);
                }

                (ev.Item as Exiled.API.Features.Items.Firearm).Ammo = 8;
                grenade._playerDamageOverDistance.keys = keyframes.ToArray();
                if (explode)
                    grenade.Network_syncTargetTime = 0.001;
            }
        }

        private void Player_UnloadingWeapon(UnloadingWeaponEventArgs ev)
        {
            if (ev.Item.Serial == Serial)
            {
                ev.IsAllowed = false;
                ev.Player.SendFormattedMsg("item", "<color=#01F1F1>自定义物品</color>", "此武器不能被卸载弹药", 2,
                    MsgType.Failed_Response, ScreenLocation.CenterTop, true);
            }
        }
    }
}